#include "PlayerView.hpp"
#include <cassert>
#include <algorithm>
#include "ChessGame.hpp"

struct PieceMarkIsZero : public unary_function<pair<Piece*, unsigned int>* , bool>
{
	PieceMarkIsZero()
	{}
	
	bool operator()(pair<Piece*, unsigned int>* p)
	{	return (p->second == 0);	}
};

PlayerView::PlayerView(Chess::Color color)
{
	try
	{		
		this->color = color;
		this->refresh();
	}
	catch(Exception* e)
	{	throw e;	}
}


PlayerView::~PlayerView()
{
	try
	{
		map<Piece*, PieceWidget*>::iterator it;
		
		for (it = w_pieces.begin() ; it != w_pieces.end() ; it++)
		{	it->second->del();	}
		
		w_pieces.clear();
	}
	catch(Exception* e)
	{	throw e;	}
}


void PlayerView::refresh()
{
	try
	{
		// 1. refresh pieces
		list<Piece*>::const_iterator 				it;
		map<Piece*, unsigned int>			marks;
		map<Piece*, PieceWidget*>::iterator	ip;
		map<Piece*, unsigned int>::iterator is;
		Piece*								piece = 0;
		//WARNING !
		Player*						player = &Chess::getInstance()->getPlayer(color);
		
		// 1.1 adding mark 0 to all pieces
		for (ip = w_pieces.begin() ; ip != w_pieces.end() ; ip++)
		{	marks[ip->first] = 0;	}
		
		// 1.2 for each pieces of the player, we looking for a new piece, and set
		//		1 to the piece's mark
		for (it = player->getPieces().begin() ; it != player->getPieces().end() ; it++)
		{
			piece = *it;
			
			if (w_pieces.find(piece) == w_pieces.end())
				w_pieces[piece] = new PieceWidget(piece);
				
			marks[piece] = 1;
			w_pieces[piece]->refresh();

			if (ChessGame::getInstance()->getCurrentPlayer() == player->getColor());
			else
				w_pieces[piece]->setTransparent(true);
			
		}
		
		// 1.3 if a piece mark is at 0, it means a piece has been deleted, we delete it
		for (is = marks.begin() ; is != marks.end() ; is++)
		{
			if (is->second == 0)
			{
				w_pieces[is->first]->del();
				w_pieces.erase(is->first);
			}
		}
				
		// 1.4 we delete all the marks !
		marks.clear();
	}
	catch(Exception* e)
	{	throw e;	}
}

const map<Piece*, PieceWidget*>&	PlayerView::getPieceWidgets()
{	return (w_pieces);	}

